<template>
  <div class="p-6 space-y-6">
    <div class="text-center">
      <h2 class="text-xl font-bold text-gray-900 mb-2">语音设置</h2>
      <p class="text-gray-600">配置语音识别相关选项</p>
    </div>

    <!-- 录音模式选择 -->
    <div class="bg-white rounded-lg border border-gray-200 p-4">
      <h3 class="text-lg font-medium text-gray-900 mb-4">录音模式</h3>
      <div class="space-y-3">
        <div
          @click="selectMode('browser')"
          :class="[
            'p-4 rounded-lg border-2 cursor-pointer transition-colors',
            recordingMode === 'browser'
              ? 'border-blue-500 bg-blue-50'
              : 'border-gray-300 hover:border-gray-400'
          ]"
        >
          <div class="flex items-center justify-between">
            <div>
              <div class="font-medium text-gray-900">浏览器识别</div>
              <div class="text-sm text-gray-600 mt-1">
                使用浏览器内置的语音识别功能，响应速度快，但准确度可能较低
              </div>
            </div>
            <div v-if="recordingMode === 'browser'" class="text-blue-600">
              <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>
              </svg>
            </div>
          </div>
        </div>

        <div
          @click="selectMode('backend')"
          :class="[
            'p-4 rounded-lg border-2 cursor-pointer transition-colors',
            recordingMode === 'backend'
              ? 'border-blue-500 bg-blue-50'
              : 'border-gray-300 hover:border-gray-400'
          ]"
        >
          <div class="flex items-center justify-between">
            <div>
              <div class="font-medium text-gray-900">后端识别</div>
              <div class="text-sm text-gray-600 mt-1">
                使用服务器端语音识别，准确度更高，但需要网络连接
              </div>
            </div>
            <div v-if="recordingMode === 'backend'" class="text-blue-600">
              <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>
              </svg>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 模式说明 -->
    <div class="bg-blue-50 rounded-lg p-4">
      <h4 class="text-sm font-medium text-blue-900 mb-2">模式说明</h4>
      <div class="text-sm text-blue-800 space-y-2">
        <div v-if="recordingMode === 'browser'">
          <p><strong>浏览器识别模式：</strong></p>
          <ul class="list-disc list-inside space-y-1 mt-1">
            <li>使用浏览器内置的Web Speech API</li>
            <li>响应速度快，无需网络传输</li>
            <li>支持实时语音识别</li>
            <li>准确度取决于浏览器实现</li>
          </ul>
        </div>
        <div v-else>
          <p><strong>后端识别模式：</strong></p>
          <ul class="list-disc list-inside space-y-1 mt-1">
            <li>使用服务器端语音识别服务</li>
            <li>准确度更高，支持更多语言</li>
            <li>需要网络连接</li>
            <li>支持离线音频文件识别</li>
          </ul>
        </div>
      </div>
    </div>

    <!-- 麦克风权限设置 -->
    <div class="bg-white rounded-lg border border-gray-200 p-4">
      <h3 class="text-lg font-medium text-gray-900 mb-4">麦克风权限</h3>
      <div class="space-y-4">
        <!-- 权限状态 -->
        <div class="flex items-center justify-between">
          <span class="text-sm text-gray-700">权限状态:</span>
          <span 
            :class="[
              'text-sm font-medium',
              permissionStatus === 'granted' ? 'text-green-600' : 
              permissionStatus === 'denied' ? 'text-red-600' : 
              'text-orange-600'
            ]"
          >
            {{ 
              permissionStatus === 'granted' ? '✅ 已授权' : 
              permissionStatus === 'denied' ? '❌ 被拒绝' : 
              '⚠️ 未知' 
            }}
          </span>
        </div>

        <!-- 权限请求按钮 -->
        <button
          @click="requestMicrophonePermission"
          :disabled="permissionStatus === 'granted'"
          :class="[
            'w-full px-4 py-2 rounded-lg text-sm font-medium transition-colors',
            permissionStatus === 'granted' 
              ? 'bg-green-100 text-green-700 cursor-not-allowed' 
              : 'bg-blue-600 text-white hover:bg-blue-700'
          ]"
        >
          {{ 
            permissionStatus === 'granted' ? '✅ 麦克风权限已获取' : 
            '🎤 请求麦克风权限' 
          }}
        </button>

        <!-- 权限说明 -->
        <div class="text-xs text-gray-600 bg-gray-50 p-3 rounded-lg">
          <p class="font-medium mb-1">权限说明：</p>
          <ul class="list-disc list-inside space-y-1">
            <li>麦克风权限用于语音识别功能</li>
            <li>权限仅在当前网站有效</li>
            <li>可以在浏览器设置中随时修改</li>
            <li>建议选择"始终允许"以获得最佳体验</li>
          </ul>
        </div>
      </div>
    </div>

    <!-- 测试按钮 -->
    <div class="text-center">
      <button
        @click="testCurrentMode"
        class="btn-primary"
      >
        测试当前模式
      </button>
    </div>

    <!-- 返回按钮 -->
    <div class="text-center">
      <button
        @click="goBack"
        class="btn-secondary"
      >
        返回语音输入
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';

const recordingMode = ref<'browser' | 'backend'>('browser');
const permissionStatus = ref<'granted' | 'denied' | 'unknown' | ''>('');

onMounted(async () => {
  // 从localStorage读取保存的模式
  const savedMode = localStorage.getItem('smartinput-voice-mode');
  if (savedMode === 'browser' || savedMode === 'backend') {
    recordingMode.value = savedMode;
  }
  
  // 检查麦克风权限状态
  await checkMicrophonePermission();
});

const selectMode = (mode: 'browser' | 'backend') => {
  recordingMode.value = mode;
  // 保存到localStorage
  localStorage.setItem('smartinput-voice-mode', mode);
  
  // 显示确认消息
  const modeName = mode === 'browser' ? '浏览器识别' : '后端识别';
  alert(`已切换到${modeName}模式`);
};

const testCurrentMode = () => {
  const modeName = recordingMode.value === 'browser' ? '浏览器识别' : '后端识别';
  alert(`当前模式：${modeName}\n\n请在语音输入页面测试录音功能`);
};

// 检查麦克风权限
const checkMicrophonePermission = async (): Promise<boolean> => {
  try {
    console.log('检查麦克风权限...');
    
    // 检查是否支持现代麦克风API
    if (!navigator.mediaDevices?.getUserMedia) {
      console.warn('浏览器不支持现代麦克风API');
      permissionStatus.value = 'unknown';
      return false;
    }
    
    // 尝试获取权限
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    stream.getTracks().forEach(track => track.stop()); // 立即停止录音
    console.log('麦克风权限已获取');
    permissionStatus.value = 'granted';
    return true;
  } catch (error) {
    console.warn('麦克风权限检查失败:', error);
    permissionStatus.value = 'denied';
    return false;
  }
};

// 请求麦克风权限
const requestMicrophonePermission = async () => {
  console.log('请求麦克风权限...');
  
  try {
    if (!navigator.mediaDevices?.getUserMedia) {
      throw new Error('浏览器不支持麦克风API');
    }
    
    console.log('使用现代API请求权限...');
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    
    if (stream) {
      stream.getTracks().forEach(track => track.stop()); // 立即停止
      permissionStatus.value = 'granted';
      
      // 获取设备信息
      const audioTracks = stream.getAudioTracks();
      const deviceInfo = audioTracks.length > 0 ? audioTracks[0].label : '未知设备';
      
      alert(`✅ 麦克风权限获取成功！\n\n设备: ${deviceInfo}\n\n现在可以正常使用语音录音功能了。`);
      console.log('权限请求成功，设备:', deviceInfo);
    }
    
  } catch (error: any) {
    console.error('权限请求失败:', error);
    permissionStatus.value = 'denied';
    
    let errorMessage = '麦克风权限请求失败';
    
    if (error.name === 'NotAllowedError') {
      errorMessage = '麦克风权限被拒绝\n\n请尝试：\n1. 刷新页面后重试\n2. 在浏览器设置中允许麦克风权限\n3. 尝试使用Chrome浏览器';
    } else if (error.name === 'NotFoundError') {
      errorMessage = '未找到麦克风设备\n\n请检查：\n1. 设备是否有麦克风硬件\n2. 麦克风是否被其他应用占用';
    } else if (error.name === 'NotSupportedError') {
      errorMessage = '浏览器不支持音频录制\n\n建议：\n1. 使用Chrome浏览器\n2. 使用Safari浏览器';
    } else if (error.name === 'SecurityError') {
      errorMessage = '安全错误\n\n请在HTTPS环境下使用此功能，或使用localhost访问';
    } else if (error.message === '浏览器不支持麦克风API') {
      errorMessage = '浏览器不支持麦克风API\n\n建议：\n1. 使用Chrome浏览器\n2. 使用Safari浏览器\n3. 更新浏览器版本';
    }
    
    alert(errorMessage);
  }
};

const goBack = () => {
  // 触发父组件返回语音输入页面
  const event = new CustomEvent('voice-settings-back');
  window.dispatchEvent(event);
};
</script>

<style scoped>
.btn-primary {
  @apply bg-blue-600 text-white font-medium py-3 px-4 rounded-lg hover:bg-blue-700 transition-colors;
}

.btn-secondary {
  @apply bg-gray-600 text-white font-medium py-3 px-4 rounded-lg hover:bg-gray-700 transition-colors;
}
</style> 